/**
 * Copyright (C) 2008 aileron.cc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cc.aileron.web.openid.process;

import static cc.aileron.wsgi.navigation.WsgiNavigation.State.Continue;
import static cc.aileron.wsgi.navigation.WsgiNavigation.State.NotFound;

import java.util.List;

import org.openid4java.consumer.ConsumerManager;
import org.openid4java.message.AuthRequest;

import cc.aileron.web.openid.resources.OpenIdResource;
import cc.aileron.wsgi.WsgiProcess;
import cc.aileron.wsgi.context.WsgiProcessContext;
import cc.aileron.wsgi.navigation.WsgiNavigation;

import com.google.inject.Inject;

/**
 * openid provider　認証要求処理
 * @author Aileron
 *
 */
public class RequestProcess implements WsgiProcess<OpenIdResource>
{
    @Override
    public WsgiNavigation doProcess(final OpenIdResource p) throws Exception
    {
        if(p.id==null)
        {
            return NotFound.navigation();
        }
        final List<?> discoveries = consumerManager.discover(p.id);
        p.discovered = consumerManager.associate(discoveries);
        
        final String returnURL = process.getRequestURL() + "?verified" ;
        final AuthRequest authRequest = consumerManager.authenticate(p.discovered, returnURL);
        p.openIdProviderUrl = authRequest.getDestinationUrl(true);
        
        return Continue.navigation();
    }
    
    /**
     * constractor injection
     * @param process
     * @param consumerManager
     */
    @Inject
    public RequestProcess(
            final WsgiProcessContext process,
            final ConsumerManager consumerManager)
    {
        this.process = process;
        this.consumerManager = consumerManager;
    }
    
    /**
     * context:process
     */
    private final WsgiProcessContext process;
    
    /**
     * consumer-manager
     */
    private final ConsumerManager consumerManager;
}